#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import json
from redis import log
from common.parse_parafile import ParamFileUtil
from redis.common.const import SysStdData
from validation.common.json_util import find_all_value_by_key
from validation.validator import ParamValidator


def get_repository_by_type(repositories, repo_type):
    for repo in repositories:
        if int(repo['repositoryType']) == repo_type:
            return repo
    return {}


def get_remote_path_by_type(remote_paths, storage_type):
    for path in remote_paths:
        if int(path['type']) == storage_type:
            return path
    return {}


def get_env_value(key):
    env_json = json.loads(SysStdData.SYS_STDIN)
    value = env_json.get(key, '')
    return value


def redis_parse_param_with_jsonschema(pid):
    """
    func: redis_parse_param_with_jsonschema()
    参数校验，校验"common schema", "redis schema", 和额外的"jobInfo schema"
    :param pid: 任务pid: int
    :return file_content: json string
    """
    path = "redis/jsonschema/redis_base_define.json"
    file_content = ParamFileUtil.parse_param_file_and_valid_by_schema(pid, path)

    job_info_path = "redis/jsonschema/job_info_define.json"
    job_info_list = find_all_value_by_key(file_content, "jobInfo")
    for job_info in job_info_list:
        if job_info:
            ParamValidator.valid_data_by_schema(json.loads(job_info), job_info_path)

    log.info("Param is valid!")
    return file_content
